package hk.cic.cwrs.bio.integration;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

import com.cily.utils.log.L;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Locale;

import hk.cic.cwrs.driver.CICdevice;

/**
 * Created by raymondsung on 7/7/2015.
 */
public class BiometricDeviceService extends Service {
    private static boolean bCICDevice = false;

    static {
        try {
//            File libFile = new File("/system/lib/iinterface.so");
//            if (libFile.exists()) {
//                System.load("/system/lib/iinterface.so");
                System.loadLibrary("iinterface");
                bCICDevice = true;
//            }
            L.e("BiometricDeviceService", "no loadLibrary");
        } catch (Exception e) {
            L.e("BiometricDeviceService", "Cannot Load iinterface.so - Probably non-CIC Device");
        }

    }

    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        L.e("BiometricDeviceService", "onBind");
        L.e("BiometricDeviceService", mBinder.toString());
        return mBinder;
    }

    private void send_wiegand(long MachineID) {
        long bitcheck = 0;
        String p1 = "", p2 = "";
        for (int i = 0; i < 16; i++) {
            p1 = ((MachineID & 0x00010000) != 0 ? "1" : "0") + p1;
            p2 = ((MachineID & 0x00000001) != 0 ? "1" : "0") + p2;
            bitcheck ^= MachineID;
            MachineID = (MachineID >> 1) & 0x7FFF7FFF;
        }
        String strWiegand = ((bitcheck & 0x10000) != 0 ? "1" : "0") + p1 + p2 + ((bitcheck & 0x1) != 0 ? "0" : "1");
        L.e("Wiegand String", strWiegand);
        if (!bCICDevice)
            L.e("sendWiegand", "Non CIC Device - Wiegand signal not sent");
        else {
            CICdevice.SendWiegand(strWiegand);
        }
    }

    private final IBioTemplateService.Stub mBinder = new IBioTemplateService.Stub() {
        @Override
        public String RequestTemplate(String sessionId) throws RemoteException {
            L.e("RequestTemplate", "sessionId:" + sessionId);
            // return "123456789";
            String strTemplate = "{\"SessionId\":\"" + sessionId + "\", \"Template\": \"AABBCCDDEEFF1122\", \"Status\":\"1\"}";
            L.e("Request Template", "return:" + strTemplate);
            Intent intent = new Intent("WriteTemplate");
            intent.putExtra("SessionID", sessionId);
            intent.putExtra("TemplateString", strTemplate);
            sendBroadcast(intent);
            return strTemplate;
        }

        @Override
        public int SetTemplateMode(int templateMode) throws RemoteException {
            L.e("SetTemplateMode", "templateMode:" + templateMode);
            return 1;
        }

        @Override
        public String VerifyTemplate(String sessionId, String CWRNo, String template, String writeDate, String writerId, String serialNo, String greenCardExpire) throws RemoteException {
            L.e("BiometricDeviceService", "Enter VerifyTemplate");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
            String logmsg = sdf2.format(new java.util.Date()) + " sessionId:" + sessionId + ", CWRNo:" + CWRNo + ", template:" + template + ", writeDate:" + writeDate + ", writeId:" + writerId + ", SerialNo:" + serialNo + ", greenCardExpire: " + greenCardExpire;
            long id = 0xF0F05A5A;
            if (CWRNo != null) {
                if (CWRNo.startsWith("CWR")) {
                    id = Long.parseLong(CWRNo.substring(3));
                    L.e("VerifyTemplate", "Use CWR No. for ID:" + id);
                }
            } else {
                id = Long.parseLong(serialNo.substring(0, 16));
                L.e("VerifyTemplate", "Use serial No. (First 4 bytes)::" + id);
            }
            L.e("VerifyTemplate", "Before Send Wiegand");
            send_wiegand(id);
            L.e("VerifyTemplate", "params:" + logmsg);
            String strReturn = "{\"SessionId\":\"" + sessionId + "\", \"CWRNo\": \"" + CWRNo + "\", \"Result\":\"1\", \"Datetime\": \"" + sdf.format(new java.util.Date()) + "\"}";
            L.e("VerifyTemplate", "return:" + strReturn);
            Intent intent = new Intent("LogResult");
            intent.putExtra("InputParams", logmsg);
            intent.putExtra("ReturnCode", strReturn);
            sendBroadcast(intent);
            L.e("VerifyTemplate", "sent broadcast message");
            return strReturn;
        }
    };
}
